package com.zy.web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.pojo.ResultInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();

        // 获得用户请求的URI
        String path = servletRequest.getRequestURI();
        System.out.println(path);

        // 除去 静态资源，登录路径，以及已经登录过后的请求
        if (path.contains("static") || path.contains("login") || session.getAttribute("employee") != null) {
            chain.doFilter(request, response);
        } else {
            /*ObjectMapper mapper = new ObjectMapper();
            servletResponse.setContentType("application/json;charset=utf-8");
            ResultInfo resultInfo = new ResultInfo(300, "您还未登陆，请登录", null);
            mapper.writeValue(servletResponse.getOutputStream(), resultInfo);*/
            servletResponse.sendRedirect("login.html");
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
